import redis
from common.utils.config_util import EnvConfig


class RedisUtil:
    def __init__(self, which=None):
        config = EnvConfig.get_config()
        which = which if which else 'rabbit_platform'
        redis_config = config['redis'][which]
        host = redis_config['host']
        port = redis_config['port']
        username = redis_config['username']
        password = redis_config['password']
        self.conn = redis.Redis(host=host, port=port, username=username, password=password)

    # 字符串存
    def set_str(self, key, value, time=0):
        if time == 0:
            self.conn.set(key, value)
        else:
            self.conn.set(key, value, time)

    # 字符串取
    def get_str(self, key):
        return self.conn.get(key)

    # 字符串删除
    def del_str(self, key):
        return self.conn.delete(key)

    # 集合存
    def insert_set(self, key, value):
        # for i in value:
        self.conn.sadd(key, value)

    # 集合取
    def find_set(self, key):
        value = self.conn.smembers(key)
        if value:
            list = []
            for i in value:
                list.append(str(i, encoding='utf8'))
            return list
        else:
            return None

    # hash 存
    def insert_hash(self, key, params, value):
        self.conn.hset(key, params, value)

    # hash 取一个属性
    def get_value(self, key, params):
        return self.conn.hget(key, params)

    # hash 获取多个
    def get_all_value(self, key):
        return self.conn.hgetall(key)

    # hash 删除
    def del_hash(self, key, params):
        self.conn.hdel(key, params)

    # list存
    def list_push(self, key, val):
        self.conn.lpush(key, val)

    # list 取
    def list_pop(self, key):
        return self.conn.rpop(key)

    # list长度
    def list_len(self, key):
        if self.conn.exists(key):
            return self.conn.llen(key)
        else:
            return 0


if __name__ == '__main__':
    r = RedisUtil('user_interface')
    r.set_str('name', 'xiaoming', 100)
    result = r.get_str('name')
    print(result)
    r.del_str('name')
    print(r.get_str('no'))









